package asyncudp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.Timer;
import java.util.TimerTask;

public final class TheMomentServer {

    private static final String REMOTE_HOST = "127.0.0.1";
    private static final int REMOTE_PORT = 7685;
    private static final int LOCAL_PORT = Integer.parseInt(System.getProperty("port", "7686"));
    private static ChannelFuture channelFuture;

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {

            Bootstrap b = new Bootstrap();
            b.group(group)

             .channel(NioDatagramChannel.class)

             // .localAddress(PORT)
             .handler(new TheMomentServerHandler());

            // b.bind(PORT).sync().channel().closeFuture().await();

            channelFuture = b.bind(LOCAL_PORT);

            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {

                    Timer timer = new Timer();

                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            channelFuture.channel().writeAndFlush(new DatagramPacket(
                                Unpooled.copiedBuffer("[SERVER] Delay Send??? 5000ms.", CharsetUtil.UTF_8),
                                new InetSocketAddress(REMOTE_HOST, REMOTE_PORT)
                            ));
                        }
                    }, 5000);
                }
            });

        } finally {
            // group.shutdownGracefully();
        }
    }
}